package com.hgc.ch04.rw;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by 01367627 on 2019/7/10.
 */
public class GoodsInfoServiceRWImpl implements IGoodsInfoService {

    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private Lock readLock = readWriteLock.readLock();
    private Lock writeLock = readWriteLock.writeLock();

    private GoodsInfo goodsInfo;

    public GoodsInfoServiceRWImpl(GoodsInfo goodsInfo) {
        this.goodsInfo = goodsInfo;
    }

    @Override
    public void getNum() {
        readLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "读到数据为：" + goodsInfo.getNum());
            Thread.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readLock.unlock();
        }
    }

    @Override
    public void setNum(int num) {
        writeLock.lock();
        try {
            goodsInfo.setNum(num);
            System.out.println(Thread.currentThread().getName() + "写入数据：" + num);
            Thread.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            writeLock.unlock();
        }
    }
}
